/*
 * @Author: yangzonglong
 * @Date: 2021-03-08 13:28:57
 * @version: v1.0.0
 * @Descripttion: 获取组件定义的props、更改props的方法
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 16:19:25
 * @Auditor:
 */
import update from 'immutability-helper';
import useFdStore from './useFdStore';
import { ActionTypes } from './../reducer';

const useControlOptions = <T>(propName?: string) => {
  const {
    state: { curControl },
    dispatch,
  } = useFdStore();


  /**
   * 修改控件FormItemProps
   * @param {string} k 字段名
   * @param {any} value 字段值
   */
  const changeFormItemProps = (k: string, value: any) => {
    if (!curControl) return;
    dispatch({
      type: ActionTypes.SYNC_CUR_CONTROL,
      curControl: update(curControl, {
        options: {
          formItemProps: {
            [k]: {
              $set: value,
            },
          },
        },
      }),
    });
  };

  /**
   * 修改控件的props
   * @param {string} k 字段名
   * @param {any} value 字段值
   * @param {boolean} mergeOptions 为true时则直接合并在options, fasle时则合并options下的属性
   */
  const changeControlProps = (k: string, value: any, mergeOptions?: boolean) => {
    if (!curControl) return;

    if (propName && !mergeOptions) {
      dispatch({
        type: ActionTypes.SYNC_CUR_CONTROL,
        curControl: update(curControl, {
          options: {
            [propName]: {
              $set: {
                [k]: value,
              },
            },
          },
        }),
      });
    } else {
      dispatch({
        type: ActionTypes.SYNC_CUR_CONTROL,
        curControl: update(curControl, {
          options: {
            [k]: { $set: value },
          },
        }),
      });
    }
  };

  /**
   * 修改table当前的选择项
   */
  const changeTableCurrent = (curColumn: any, fn: (data: any) => void) => {
    if (!curControl) return;
    dispatch({
      type: ActionTypes.CHANGE_TABLECURRENT,
      curColumn: { fn, curColumn: { ...curColumn } },
    });
  };

  /**
 * 修改dataList当前的选择项
 */
  const changeDataListCurrent = (curColumn: any, fn: (data: any) => void) => {
    if (!curControl) return;
    dispatch({
      type: ActionTypes.CHANGE_DATALISTCURRENT,
      curColumn: { fn, curColumn: { ...curColumn } },
    });
  };

  return {
    id: curControl?.id,
    options: curControl?.options as T,
    changeFormItemProps,
    changeControlProps,
    changeTableCurrent,
    changeDataListCurrent,
  };
};

export default useControlOptions;
